package GUI;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import map.Resolution;
import map.Tile;

import Player.Faction;
import Player.Race;

import controller.ImageLoader;
import controller.LocalManager;


public class NewGamePanel extends JPanel{

	public NewGamePanel(TopLevelFrame container){
		this.container = container;
		avatarBox = "Order of the stick";
		avatarIndex = 1;
		globalPanel = new JPanel();
		globalPanel.setLayout(new BoxLayout(globalPanel, BoxLayout.Y_AXIS));
		history = new JTextArea(5, 7);
		history.setLineWrap(true);
		JScrollPane historyScr = new JScrollPane(history);
		historyScr.setPreferredSize(new Dimension(250, 150));
		//total
		globalPanel.add(Box.createRigidArea(new Dimension(0, 30)));
		globalPanel.add(createImagePanel());
		globalPanel.add(new JSeparator(JSeparator.HORIZONTAL));
		globalPanel.add(Box.createRigidArea(new Dimension(0, 10)));
		globalPanel.add(createChosePanel());
		globalPanel.add(Box.createRigidArea(new Dimension(0, 30)));
		globalPanel.add(historyScr);
		this.setLayout(new BorderLayout());
		this.add(globalPanel, BorderLayout.CENTER);
		this.add(createButtonsPanel(), BorderLayout.SOUTH);
		this.add(createBoxPanel(), BorderLayout.WEST);
	}
	
	public JPanel createImagePanel(){
		JLabel next = new JLabel(">");
		JLabel previous = new JLabel("<");
		next.setFont(normal);
		previous.setFont(normal);
		next.addMouseListener(new MouseClick(next, true));
		previous.addMouseListener(new MouseClick(previous, false));
		avatar = ImageLoader.getPlayerImage(resolution, avatarBox, avatarIndex);
		image = new JLabel(avatar);
		image.setPreferredSize(new Dimension(100, 200));
		JPanel p = new JPanel(new BorderLayout());
		p.setPreferredSize(new Dimension(140, 200));
		p.add(previous, BorderLayout.WEST);
		p.add(image, BorderLayout.CENTER);
		p.add(next, BorderLayout.EAST);
		return p;
	}
	
	public JPanel createChosePanel(){
		JLabel nameL = new JLabel("Nome: ");
		JLabel raceL = new JLabel("Razza: ");
		JLabel factionL = new JLabel("Fazione: ");
		name = new JTextField(10);
		oldTextTip = ImageLoader.getPlayerImage(avatarBox).get(avatarIndex).getName();
		name.setText(oldTextTip);
		
		ArrayList<String> temp = new ArrayList<String>();
		for(Race r : Race.values()){
			temp.add(r.getRaceName());
		}
		race = new JComboBox<String>(temp.toArray(new String[0]));
		temp = new ArrayList<String>();
		for(Faction f : Faction.values()){
			temp.add(f.getFactionName());
		}
		faction = new JComboBox<String>(temp.toArray(new String[0]));
		JPanel p = new JPanel();
		p.add(nameL);
		p.add(name);
		p.add(raceL);
		p.add(race);
		p.add(factionL);
		p.add(faction);
		return p;
	}
	
	public JPanel createBoxPanel(){
		ArrayList<String> temp = new ArrayList<String>();
		for(String boxName : ImageLoader.getPlayerImageBox()){
			temp.add(boxName);
		}
		box = new JComboBox<String>(temp.toArray(new String[0]));
		box.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if(e.getStateChange() == ItemEvent.SELECTED){
					avatarBox = (String)e.getItem();
					avatarIndex = 0;
					listedImages.removeListSelectionListener(selection);
					listModel.removeAllElements();
					for(Tile image: ImageLoader.getPlayerImage(avatarBox))
						listModel.addElement(image.getName());
					refreshImage();
					listedImages.addListSelectionListener(selection);
				}
			}
		});
		
		selection = new SelectionListener();
		listModel = new DefaultListModel<String>();
		for(Tile image: ImageLoader.getPlayerImage(avatarBox))
			listModel.addElement(image.getName());
		listedImages = new JList<String>(listModel);
		listedImages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listedImages.setLayoutOrientation(JList.VERTICAL);
		listedImages.addListSelectionListener(selection);
		box.setSelectedIndex(temp.indexOf(avatarBox));
		listedImages.setSelectedIndex(avatarIndex);
		JScrollPane listScr = new JScrollPane(listedImages);
		JPanel p = new JPanel();
		p.setLayout(new BorderLayout());
		p.add(box, BorderLayout.NORTH);
		p.add(listScr, BorderLayout.CENTER);
		return p;
	}
	
	public JPanel createButtonsPanel(){
		JButton confirm = new JButton("Conferma");
		confirm.addActionListener(new ConfirmListener());
		JPanel p = new JPanel();
		p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
		p.add(Box.createHorizontalGlue());
		p.add(confirm);
		return p;
	}
	
	public void refreshImage(){
		listedImages.setSelectedIndex(avatarIndex);
		avatar = ImageLoader.getPlayerImage(resolution, avatarBox, avatarIndex);
		String newName = ImageLoader.getPlayerImage(avatarBox).get(avatarIndex).getName();
		if(name.getText().length() == 0 || name.getText().equalsIgnoreCase(oldTextTip)){
			name.setText(newName);
			oldTextTip = newName;
		}
		image.setIcon(avatar);
		image.revalidate();
		name.revalidate();
		listedImages.revalidate();
	}
	
	class MouseClick implements MouseListener{
		public MouseClick(JLabel source, boolean next){
			this.source = source;
			this.next = next;
		}
		public void mouseClicked(MouseEvent e) {
			int max = ImageLoader.getPlayerImage(avatarBox).size();
			if(next){
				if(avatarIndex<max-1)
					avatarIndex++;
			}else{
				if(avatarIndex>0)
					avatarIndex--;
			}
			refreshImage();
		}
		public void mouseEntered(MouseEvent e) {
			source.setFont(over);
			source.revalidate();
		}
		public void mouseExited(MouseEvent e) {
			source.setFont(normal);
			source.revalidate();
		}
		public void mousePressed(MouseEvent e) {}
		public void mouseReleased(MouseEvent e) {}
		
		private boolean next;
		private JLabel source;
	}
	
	class ConfirmListener implements ActionListener{
		public void actionPerformed(ActionEvent arg0) {
			new Thread(){
        		public void run() {
        			ImageLoader.addNotifyListener(this);
        			while(!ImageLoader.isLoaded()){
        				synchronized (this) {
        					try {
        						this.wait();
        					} catch (InterruptedException ex) {
        						ex.printStackTrace();
        					}
        				}
        			}
                	//create new pg
        			LocalManager.createNew(name.getText(), Race.values()[race.getSelectedIndex()], Faction.values()[faction.getSelectedIndex()], avatarBox, avatarIndex, history.getText());
        			//create new map
        			container.createGamePanel();
        		};
        	}.start();
		}
	}
	
	class SelectionListener implements ListSelectionListener {
		public void valueChanged(ListSelectionEvent e) {
			avatarIndex = listedImages.getSelectedIndex();
			refreshImage();
		}
	}
	
	private TopLevelFrame container;
	private JComboBox<String> box, race, faction;
	private JTextField name;
	private JTextArea history;
	private JLabel image;
	private JPanel globalPanel;
	private String avatarBox, oldTextTip;
	private int avatarIndex;
	private ImageIcon avatar;
	private JList<String> listedImages;
	private DefaultListModel<String> listModel;
	private SelectionListener selection;
	private static final Resolution resolution = Resolution.VHIGH;
	private static final Font normal = new Font("Big", Font.PLAIN, 40) , over = new Font("Big", Font.BOLD, 42);;
	private static final long serialVersionUID = -8219565498866950934L;
}
